package vip.liux.contracts.infrastructure.converts;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vip.liux.contracts.shared.value.SpecDetail;
import vip.liux.core.utils.JsonUtils;

import java.util.List;

@Converter(autoApply = true)
class JsonToSpecDetailsConverter implements AttributeConverter<List<SpecDetail>, String> {
    private static final Logger log = LoggerFactory.getLogger(JsonToSpecDetailsConverter.class);

    @Setter
    private ObjectMapper objectMapper = JsonUtils.getObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<SpecDetail> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            log.warn("Failed to convert SpecDetails to JSON: {}, error: {}", attribute, e.getMessage());
            return "[]";
        }
    }

    @Override
    public List<SpecDetail> convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            log.warn("Failed to convert JSON to SpecDetails: {}, error: {}", dbData, e.getMessage());
            return List.of();
        }
    }
}